package com.yizhi.controller;

import cn.hutool.core.bean.BeanUtil;
import com.yizhi.domain.dto.UserFormDTO;
import com.yizhi.domain.entityDO.UserDO;
import com.yizhi.domain.vo.UserVO;
import com.yizhi.service.IUserService;
import com.yizhi.util.ApiResult;
import com.yizhi.util.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户(也就是账号管理)
 * </p>
 *
 * @author zhouyihe
 * @since 2024-04-16
 */
@Api(tags = "用户账号管理接口")
@RequestMapping("/user")
@RestController
@RequiredArgsConstructor
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
    
    @ApiOperation("新增用户接口")
    @PostMapping
    public ApiResult saveUser(@RequestBody UserFormDTO userDTO){
        log.info("新增用户:{}",userDTO);
        // 1.把DTO拷贝到PO
        UserDO user = BeanUtil.copyProperties(userDTO, UserDO.class);
        // 2.新增
        boolean save  = userService.save(user);
        return save ? ApiResult.success("新增成功"):ApiResult.error("新增失败");
    }
    
    @ApiOperation("删除用户接口")
    @DeleteMapping("{ids}")
    public ApiResult deleteUserById(@ApiParam("用户id集合") @PathVariable("ids") List<Integer> ids){
        log.info("删除id为:{}的用户",ids);
        boolean b = userService.removeByIds(ids);
        return b ? ApiResult.success("删除成功"):ApiResult.error("删除失败");
    }
    
    @ApiOperation("根据id查询用户接口")
    @GetMapping("{id}")
    public UserVO queryUserById(@ApiParam("用户id") @PathVariable("id") Long id){
        log.info("根据id为:{}查询用户",id);
        return BeanUtil.copyProperties(userService.getById(id), UserVO.class);
    }
    
    @ApiOperation("根据条件分页查询用户接口")
    @GetMapping("/page")
    public ApiResult<PageResult> queryUsersPage(@RequestBody UserFormDTO userFormDTO){
        log.info("根据条件分页查询用户:{}",userFormDTO);
        return ApiResult.success(userService.pageQuery(userFormDTO));
    }
    
    @ApiOperation("修改用户")
    @PutMapping()
    public ApiResult updateUser(@RequestBody UserFormDTO userFormDTO){
        log.info("修改用户:{}",userFormDTO);
        UserDO user = BeanUtil.copyProperties(userFormDTO, UserDO.class);
        boolean b = userService.updateById(user);
        return b ? ApiResult.success("修改成功"):ApiResult.error("修改失败");
    }
}
